﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using ebay.Utility;

namespace ebay.Dal
{
    //订单审核：
    public class OrdersAudit
    {      
        //搜索的审核记录
        public DataTable GetOrderShePara(string BuilderWhere, List<SqlParameter> list)
        {
            string cmdText = "Select EbayUserId ,OrderId From Orders Where OrderStatusId =1 {0}";
            cmdText = string.Format(cmdText, BuilderWhere);
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataTable(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, list.Count == 0 ? null : list.ToArray());
            return dt;
        }
        
        //客服审核记录
        public void OrderShe(int k3UserId,string BuilderWhere, List<SqlParameter> sqllist,string userId,ref string retMsg)
        {            
            DataTable dt = GetOrderShePara(BuilderWhere, sqllist);
            if(dt==null)
            {         
                FileLog.CreateLog(LogAction.OrderCheck, "", "无可审核数据！..>>");
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string ebayUserId = dt.Rows[i]["EbayUserId"].ToString();
                string orderId = dt.Rows[i]["OrderId"].ToString();
                string cmdText = @"Select top 1 c.SaleDate,isnull(d.createdatetime,'1900-1-1') as createdatetime From Orders c
                            Left Outer Join PPOrder d on c.EbayUserId = d.EbayUserId And c.PayPalTransactionId = d.TransactionId
                            Where c.EbayUserId = @EbayUserId And c.OrderId = @OrderId;
                            Select isnull(b.FitemId,0) as FitemId,a.Quantity,a.SalePrice,isnull(d.Currency,'GBP') as Currency,isnull(a.OrderLineItemId,'') as Lid,c.DeliveryId,a.WarehouseId From Orders c
                            Left Outer Join CustomerResolve a On a.OrderLineItemId = c. OrderLineItemId And a.EbayUserId = c.EbayUserId
                            Left Outer Join Product b on a.ProductId = b.ProductId
                            Left Outer Join PPOrder d on c.EbayUserId = d.EbayUserId And c.PayPalTransactionId = d.TransactionId
                            Where c.EbayUserId = @EbayUserId And c.OrderId = @OrderId";
                try
                {
                    SqlParameter[] p = { 
                                           new SqlParameter("@EbayUserId",SqlDbType.VarChar),
                                           new SqlParameter("@OrderId",SqlDbType.VarChar)
                                           };
                    p[0].Value = ebayUserId;
                    p[1].Value = orderId;
                    DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, p);                    
                    DataTable table = ds.Tables[1];
                    DataTable t_title = ds.Tables[0];
                    if (table.Select("Lid = ''").Length > 0)
                    {
                        FileLog.CreateLog(LogAction.OrderCheck, "", "订单:" + orderId + "中还有未解析的CustomLable,不能发货>>");   
                    }
                    else if (table.Select("FitemId <= 0").Length > 0)
                    {                     
                        FileLog.CreateLog(LogAction.OrderCheck, "", "订单:" + orderId + "中还有商品未进K3>>");   
                    }
                    else if (table.Select("DeliveryId = 0").Length > 0)
                    {                   
                        FileLog.CreateLog(LogAction.OrderCheck, "", "订单:" + orderId + "中还未选择发货方式>>");   
                    }
                    else
                    {                        
                        DateTime saleDate = Convert.ToDateTime(t_title.Rows[0][0]);
                        DateTime pDate = Convert.ToDateTime(t_title.Rows[0][1]);
                        System.Collections.Generic.List<ebay.Model.CustomerResolveContext> list = new System.Collections.Generic.List<ebay.Model.CustomerResolveContext>();

                        foreach (DataRow r in table.Rows)
                        {
                            ebay.Model.CustomerResolveContext m = new ebay.Model.CustomerResolveContext();
                            m.Currency = r["Currency"].ToString();
                            m.FItemId = Convert.ToInt32(r["FitemId"]);
                            m.Quantity = Convert.ToInt32(r["Quantity"]);
                            m.SalePrice = Convert.ToInt32(r["SalePrice"]);
                            m.FstockId = Convert.ToInt32(r["WarehouseId"]);
                            list.Add(m);
                        }

                        string msg = "";
                        Orders os = new Orders();
                        bool val = os.T_F_Order(k3UserId, ebayUserId, orderId, userId, 0, 0, saleDate, pDate, list,ref msg);//生成发货单
                        if (!val)
                        {                           
                            FileLog.CreateLog(LogAction.OrderCheck, "", "订单:" + orderId + "生成发货单失败>>");
                        }
                        else
                        {
                            FileLog.CreateLog(LogAction.OrderCheck, "", "订单:" + orderId + "成功生成发货单！..>>");
                        }
                    }
                }
                catch (Exception ex)
                {               
                    FileLog.CreateLog(LogAction.OrderCheck, "", "订单:" + orderId + "操作失败,原因:"+ex.ToString());
                    continue;
                }
            }          
        }

        //******************审核操作写日志*********************************** 
        public void LogTitle()
        {
            FileLog.CreateLog(LogAction.OrderCheck, "", "===========================订单客服审核日志=============================");

            FileLog.CreateLog(LogAction.OrderCheck, "", "日志开始时间：" + DateTime.Now.ToString());
        }
        public void LogEnd()
        {
            FileLog.CreateLog(LogAction.OrderCheck, "", "日志结束时间：" + DateTime.Now.ToString());
            FileLog.CreateLog(LogAction.OrderCheck, "", "=============================本次操作结束==============================="); 
        }
        public bool LogMsg(int k3UserId, string BuilderWhere, List<SqlParameter> list, string userId, ref string retMeg)
        {
            try
            {
                this.LogTitle();
                this.OrderShe(k3UserId, BuilderWhere, list, userId, ref retMeg);
                this.LogEnd();
                return true;
            }
            catch
            {
                return false;
            }
        }

        //**********************实际邮费维护__审核****************************
        public bool RealPostage_She(string ids ,string userId)
        {
            string[] id = ids.Split(',');
            DateTime date = DateTime.Now;
            string cmdText = @"Update RealPostage set Status=1,Muser =@UserId,Auser =@UserId,Mtime=@Date,Atime=@Date where Id=@Id ";
            SqlParameter[] p ={
                                  new SqlParameter ("@UserId",SqlDbType.VarChar),
                                  new SqlParameter ("@Date",SqlDbType.DateTime),
                                  new SqlParameter ("@Id",SqlDbType.VarChar)
                              };
            int val = 0;
            try
            {
                foreach (string realpid in id)
                {
                    p[0].Value = userId;
                    p[1].Value = date;
                    p[2].Value = realpid;
                    val += SqlHelper.ExecuteNonQuery(SqlHelper.ceterDB_Conn, CommandType.Text, cmdText, p);
                    if (val > 0)
                    {
                        return true;
                    }
                }
            }
            catch
            {
                return false;
            }
            return false;
        }

        //********************************************************************
    }
}
